package com.snap.awesomeserial.serial;

import android.util.Log;

import com.snap.awesomeserial.bean.SerialPortDevice;

import java.io.IOException;
import java.util.HashMap;

/**
 * 串口通信管理者
 * 运行在Service中 、  或者单例全局可以获取
 * 可以对多个连接进行同时管理
 * 也是发送数据、接收数据的调度中心????
 */
public class SerialPortManager {

    private static final String TAG = "SerialPortManager";

    private HashMap<String, SerialPortHelper> portMap = new HashMap<>();

    private SerialPortManager() {
    }

    public static SerialPortManager getInstance() {
        return SerialPortManagerHolder.manager;
    }

    /**
     * 打开一个串口
     */
    public void open(SerialPortDevice device) {
        if (portMap.containsKey(device.getPort())) {
            Log.e(TAG, "device is already open ," + device.getPort());
            return;
        }
        SerialPortHelper serialPortHelper = new SerialPortHelper(device);
        try {
            serialPortHelper.open();
            portMap.put(device.getPort(), serialPortHelper);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭一个串口
     */
    public void close(String port) {
        if (portMap.containsKey(port)) {
            SerialPortHelper serialPortHelper = portMap.get(port);
            serialPortHelper.close();
            portMap.remove(port);
        }
    }

    public SerialPortHelper getPort(String port) {
        return portMap.get(port);
    }

    private static class SerialPortManagerHolder {
        private static final SerialPortManager manager = new SerialPortManager();
    }
}